package cmdb_info

import (
	"fmt"
	"regexp"
)

type mongoDBConnectInfo struct {
	Role             string
	ConnectionString string
	NetType          string
}

type MongoDBInfo struct {
	InstanceId             string
	MongoDBConnectInfoList []mongoDBConnectInfo
	Status                 string
	Uid                    string
	Region                 string
}

func judgeHost(connectString string) string {
	// Define the pattern to match the desired substring
	pattern := `([^\s]+\.mongodb\.rds\.aliyuncs\.com:\d+)`

	// Compile the regular expression
	re := regexp.MustCompile(pattern)

	// Find the first match in the input string
	match := re.FindStringSubmatch(connectString)

	// Check if a match is found
	if len(match) > 1 {
		return match[1]
	}

	// Return an empty string if no match is found
	return ""
}

func GetMongoDBCmdbInfo(cmdbMongoUrl string, netTypeList []string) ([]MongoDBInfo, error) {
	var mongoInfoList []MongoDBInfo
	// var netType = "VPC"
	// var netTypeList = []string{"Public"}
	// var netTypeList = []string{"Public"}
	var mongoServerRoleList = []string{"Primary", "Secondary"}
	// var primaryNetType = fmt.Sprintf("%s/Primary", netType)
	// var secondaryNetType = fmt.Sprintf("%s/Secondary", netType)
	var retData, err = GetUrl(cmdbMongoUrl)
	if err != nil {
		panic(err)
	}

	var instanceListInfo = (*retData)["data"]
	for _, instanceInfo := range instanceListInfo.([]interface{}) {
		var mongoInfo MongoDBInfo
		if instance_id, ok := instanceInfo.(map[string]interface{})["id"].(string); ok {
			mongoInfo.InstanceId = instance_id
		}
		if status, ok := instanceInfo.(map[string]interface{})["status"].(string); ok {
			mongoInfo.Status = status
		}

		if connections, ok := instanceInfo.(map[string]interface{})["data"].(map[string]interface{})["connections"].(map[string]interface{}); ok {
			for _, netType := range netTypeList {
				var monConnect mongoDBConnectInfo
				for _, mongoServerRole := range mongoServerRoleList {
					NetTypeStr := fmt.Sprintf("%s/%s", netType, mongoServerRole)
					if mongoConnect, ok := connections[NetTypeStr].([]interface{}); ok {
						for _, mongoConnectInfo := range mongoConnect {
							hostString := mongoConnectInfo.(map[string]interface{})["host"].(string)
							if retS := judgeHost(hostString); retS != "" {
								monConnect.ConnectionString = retS
								monConnect.Role = mongoServerRole
								monConnect.NetType = netType
							}
						}
					}
				}
				mongoInfo.MongoDBConnectInfoList = append(mongoInfo.MongoDBConnectInfoList, monConnect)
			}

		}

		mongoInfoList = append(mongoInfoList, mongoInfo)
	}
	return mongoInfoList, nil
}
